import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/utils/TimerUtils.dart';

class TimerWidget extends StatefulWidget {
  num time;
  String day;
  String hour;
  String min;
  String second;
  String end;
  int color;
  double fontSize;
  Function(int) onRun;
  Function onFinsh;

  TimerWidget(
    time, {
    @required onRun,
    @required onFinsh,
    day = "天",
    hour = "小时",
    min = "分钟",
    second = "秒",
    end = "",
    color = 0xFFe1251b,
    fontSize = 22.0,
  }) {
    this.time = time;
    this.onRun = onRun;
    this.onFinsh = onFinsh;
    this.hour = hour;
    this.day = day;
    this.min = min;
    this.second = second;
    this.end = end;
    this.color = color;
    this.fontSize = fontSize;
  }

  @override
  _TimerWidgetState createState() => _TimerWidgetState();
}

class _TimerWidgetState extends State<TimerWidget> {
  Timer _timer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    startTimer();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(
        TimerUtils.getTimer(widget.time,
            end: widget.end,
            day: widget.day,
            hour: widget.hour,
            min: widget.min,
            seconds: widget.second),
        style: TextStyles.custom(
            widget.fontSize, Color(widget.color), Font.PingFangMedium),
      ),
    );
  }

  void startTimer() {
    //设置 1 秒回调一次
    if(widget.time>0){
      const period = const Duration(seconds: 1);
      _timer = Timer.periodic(period, (timer) {
        widget.time--;
        //是否更新页面交给调用者处理
        widget.onRun(widget.time);

        if (widget.time <= 0) {
          //倒计时秒数为0，取消定时器
          cancelTimer();
        }
      });
    }else{
      cancelTimer();
    }

  }

  void cancelTimer() {
    if (_timer != null) {
      widget.onFinsh();
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
  }
}
